package com.wjf.birdfish.util;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
   
public final class StringHelper {

	/**
	 * 将字符串数组联合成一个字符串，数组元素中间用分隔符分开
	 * 
	 * @param seperator
	 *            分隔符
	 * @param strings
	 *            字符串数组
	 * 
	 * @return 返回字符串
	 */
	public static String join(String seperator, String[] strings) {
		int length = strings.length;
		if (length == 0)
			return "";
		StringBuffer buf = new StringBuffer(length * strings[0].length())
				.append(strings[0]);
		for (int i = 1; i < length; i++) {
			buf.append(seperator).append(strings[i]);
		}
		return buf.toString();
	}

	/**
	 * 将字符串重复Copy几次，形成新的字符串
	 * 
	 * @param string
	 *            字符串
	 * @param times
	 *            重复次数
	 * 
	 * 
	 */
	public static String repeat(String string, int times) {
		StringBuffer buf = new StringBuffer(string.length() * times);
		for (int i = 0; i < times; i++)
			buf.append(string);
		return buf.toString();
	}

	/**
	 * 将字符串中的某个字符串替换为另外一个字符串
	 * 
	 * @param template
	 *            操作的字符串
	 * @param placeholder
	 *            被替换的字符串
	 * @param replacement
	 *            替换的的字符串
	 * 
	 */
	public static String replace(String template, String placeholder,
			String replacement) {
		int loc = template.indexOf(placeholder);
		if (loc < 0) {
			return template;
		} else {
			return new StringBuffer(template.substring(0, loc)).append(
					replacement).append(
					replace(template.substring(loc + placeholder.length()),
							placeholder, replacement)).toString();
		}
	}

	/**
	 * 将字符串中的某个字符串替换为另外一个字符串，仅被替换一次
	 * 
	 * @param template
	 *            操作的字符串
	 * @param placeholder
	 *            被替换的字符串
	 * @param replacement
	 *            替换的的字符串
	 * 
	 */

	public static String replaceOnce(String template, String placeholder,
			String replacement) {
		int loc = template.indexOf(placeholder);
		if (loc < 0) {
			return template;
		} else {
			return new StringBuffer(template.substring(0, loc)).append(
					replacement).append(
					template.substring(loc + placeholder.length())).toString();
		}
	}

	/**
	 * 将字符串分割，返回数组
	 * 
	 * @param seperators
	 *            分割字符
	 * @param list
	 *            字符串
	 * 
	 * 
	 * 
	 */
	public static String[] split(String seperators, String list) {
		StringTokenizer tokens = new StringTokenizer(list, seperators);
		String[] result = new String[tokens.countTokens()];
		int i = 0;
		while (tokens.hasMoreTokens()) {
			result[i++] = tokens.nextToken();
		}
		return result;
	}

	public static String unqualify(String qualifiedName) {
		return unqualify(qualifiedName, ".");
	}

	public static String unqualify(String qualifiedName, String seperator) {
		return qualifiedName
				.substring(qualifiedName.lastIndexOf(seperator) + 1);
	}

	public static String qualifier(String qualifiedName) {
		int loc = qualifiedName.lastIndexOf(".");
		if (loc < 0) {
			return "";
		} else {
			return qualifiedName.substring(0, loc);
		}
	}

	public static String root(String qualifiedName) {
		int loc = qualifiedName.indexOf(".");
		return (loc < 0) ? qualifiedName : qualifiedName.substring(0, loc);
	}

	public static boolean booleanValue(String tfString) {
		String trimmed = tfString.trim().toLowerCase();
		return trimmed.equals("true") || trimmed.equals("t");
	}

	public static String toString(Object[] array) {
		int len = array.length;
		if (len == 0)
			return "";
		StringBuffer buf = new StringBuffer(len * 12);
		for (int i = 0; i < len - 1; i++) {
			buf.append(array[i]).append(", ");
		}
		return buf.append(array[len - 1]).toString();
	}

	public static String[] multiply(String string, Iterator placeholders,
			Iterator replacements) {
		String[] result = new String[] { string };
		while (placeholders.hasNext()) {
			result = multiply(result, (String) placeholders.next(),
					(String[]) replacements.next());
		}
		return result;
	}

	private static String[] multiply(String[] strings, String placeholder,
			String[] replacements) {
		String[] results = new String[replacements.length * strings.length];
		int n = 0;
		for (int i = 0; i < replacements.length; i++) {
			for (int j = 0; j < strings.length; j++) {
				results[n++] = replaceOnce(strings[j], placeholder,
						replacements[i]);
			}
		}
		return results;
	}

	/**
	 * 取得某一个Char字符在字符串中的个数
	 * 
	 */
	public static int getValueCount(String str, char c) {
		int n = 0;
		for (int i = 0; i < str.length(); i++) {
			char a = str.charAt(i);
			if (a == c) {
				n++;
			}
		}
		return n;
	}

	public static void main(String[] args) {
		System.out.println(StringHelper.replace("ab", "a", "b"));
	}

	public static String toString(Object obj) {
		if (obj == null || obj.toString().equals("")
				|| obj.toString().equals("null")) {
			return "";
		} else {
			String objValue = obj.toString().trim();
			return objValue;
		}
	}

	/** 截取汉字或汉字、字符混合串的前n位，如果第n位为双字节字符，则截取前n-1位 */
	public static String leftCut(String str, int n) {
		byte[] b_str = str.getBytes();
		byte[] new_str;
		int k;
		if (b_str.length < n) {
			return str;
		} else {
			if (b_str[n] < 0 && b_str[n - 1] > 0) {
				k = n - 1;
			} else {
				k = n;
			}
			new_str = new byte[k];
			for (int i = 0; i < k; i++) {
				new_str[i] = b_str[i];
			}
			return new String(new_str);
		}
	}

	/** 将 a,b,c,d, 转换成 'a','b','c','d' */
	public static String addSingleMark(String strContent) {
		String[] str = StringHelper.split(",", strContent);
		String newStr = "";
		for (int i = 0; i < str.length; i++) {
			newStr += "'" + str[i] + "',";
		}
		newStr = newStr.substring(0, newStr.length() - 1);
		return newStr;
	}

	/** 将回车换行符替换成HTML换行符* */
	public static String addBr(String Content) {
		String makeContent = new String();
		StringTokenizer strToken = new StringTokenizer(Content, "\n");
		while (strToken.hasMoreTokens()) {
			makeContent = makeContent + "<br>" + strToken.nextToken();
		}
		return makeContent;
	}

	/** 将HTML换行符替换成回车换行符* */
	public static String subtractBr(String Content) {
		String makeContent = new String();
		StringTokenizer strToken = new StringTokenizer(Content, "<br>");
		while (strToken.hasMoreTokens()) {
			makeContent = makeContent + "\n" + strToken.nextToken();
		}
		return makeContent;
	}

	/**
	 * 检查字符串是否为非零长度的有效字符串
	 * 
	 * @param var
	 *            需检查的字符串
	 * @return 不为空字符串返回true，否则返回false
	 */
	public static boolean checkString(String var) {
		boolean bRtn = true;
		if (var == null) {
			bRtn = false;
		} else {
			if (var.length() < 1)
				bRtn = false;
		}
		return bRtn;
	}

	/**
	 * 检查字符串是否是合法整数
	 * 
	 * @param var
	 *            传入需要检查的字符串
	 * @return 如果为合法整数返回true，否则返回false
	 */
	public static boolean checkInt(String var) {
		boolean bRtn = true;
		try {
			if (Integer.parseInt(var) > Integer.MAX_VALUE
					|| Integer.parseInt(var) < Integer.MIN_VALUE)
				bRtn = false;
		} catch (Exception e) {
			bRtn = false;
		}
		return bRtn;
	}
	
	public static boolean checkLong(String var) {
		boolean bRtn = true;
		try {
			Long.parseLong(var);
			bRtn = true;
		} catch (Exception e) {
			bRtn = false;
		}
		return bRtn;
	}
	
	public static boolean checkFloat(String var) {
		boolean bRtn = true;
		try {
			Float.parseFloat(var);
			bRtn = true;
		} catch (Exception e) {
			bRtn = false;
		}
		return bRtn;
	}
	
	public static boolean checkDouble(String var) {
		boolean bRtn = true;
		try {
			Double.parseDouble(var);
			bRtn = true;
		} catch (Exception e) {
			bRtn = false;
		}
		return bRtn;
	}
	
	public static boolean isNumeric(String str) {
        int begin = 0;
        boolean once = true;
        if (str == null || str.trim().equals("")) {
            return false;
        }
        str = str.trim();
        if (str.startsWith("+") || str.startsWith("-")) {
            if (str.length() == 1) {
                // "+" "-"
                return false;
            }
            begin = 1;
        }
        for (int i = begin; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                if (str.charAt(i) == '.' && once) {
                    // '.' can only once
                    once = false;
                }
                else {
                    return false;
                }
            }
        }
        if (str.length() == (begin + 1) && !once) {
            // "." "+." "-."
            return false;
        }
        return true;
    }

	
	/**
	 * 检查是否是有效的电子邮件格式
	 * @param str
	 * @return
	 */
	public static boolean checkMail(String str) {
		Pattern p = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*.\\w+([-.]\\w+)*");
		Matcher m = p.matcher(str);
		return m.matches();
	}
	
	/**
	 * 检验电子邮件格式
	 * "yuzhixinggiftedb@163com"不行
	 * "yuzhixinggiftedb@163.com"可以
	 * "yuzhixinggiftedb163.com"不行
	 * "yuzhixinggiftedb@@163.com"不行
	 */
	public static boolean checkEmailAt(String eMailAddress){
		if(eMailAddress.indexOf('@')==-1){
			return false;
		}
		else return true;
	}

	/**
	 * 检查是否为有效的电话号码
	 * @param str
	 * @return
	 */
	public static boolean checkPhone(String str) {
		Pattern p = Pattern.compile("^(\\d{3}-|\\d{4}-)?(\\d{8}|\\d{7})?(-\\d+)?$");
		Matcher m = p.matcher(str);
		return m.matches();
	}
	
	public static boolean checkMobile(String str) {
		Pattern p = Pattern.compile("^13\\d{9}$");
		Matcher m = p.matcher(str);
		return m.matches();
	}

	/**
	 * 检查是否为有效的身份证号码
	 * @param str
	 * @return
	 */
	public static boolean checkIDCard(String str) {
		
		class IDCard {
			final int[] wi = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8,
					4, 2, 1 };

			final int[] vi = { 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 };

			private int[] ai = new int[18];

			public IDCard() {
			}

			public boolean Verify(String idcard) {
				if (idcard.length() == 15) {
					idcard = uptoeighteen(idcard);
				}
				if (idcard.length() != 18) {
					return false;
				}
				String verify = idcard.substring(17, 18);
				if (verify.equals(getVerify(idcard))) {
					return true;
				}
				return false;
			}

			public String getVerify(String eightcardid) {
				int remaining = 0;
				if (eightcardid.length() == 18) {
					eightcardid = eightcardid.substring(0, 17);
				}
				if (eightcardid.length() == 17) {
					int sum = 0;
					for (int i = 0; i < 17; i++) {
						String k = eightcardid.substring(i, i + 1);
						ai[i] = Integer.parseInt(k);
					}
					for (int i = 0; i < 17; i++) {
						sum = sum + wi[i] * ai[i];
					}
					remaining = sum % 11;
				}
				return remaining == 2 ? "X" : String.valueOf(vi[remaining]);
			}
			public String uptoeighteen(String fifteencardid) {
				String eightcardid = fifteencardid.substring(0, 6);
				eightcardid = eightcardid + "19";
				eightcardid = eightcardid + fifteencardid.substring(6, 15);
				eightcardid = eightcardid + getVerify(eightcardid);
				return eightcardid;
			}

		}

		IDCard idCard = new IDCard();
		return idCard.Verify(str);
	}

	/**
	 * 检查是否为有效的网页地址
	 * @param str
	 * @return
	 */
	public static boolean checkURL(String str) {
		Pattern p = Pattern.compile("^[\\w\\.]+$");
		Matcher m = p.matcher(str);
		return m.matches();
	}

	/**
	 * 检查是否为有效的邮政编码
	 * @param str
	 * @return
	 */
	public static boolean checkZIP(String str) {
		Pattern p = Pattern.compile("^\\d{6}$");
		Matcher m = p.matcher(str);
		return m.matches();
	}
	
	/**
	 * 检查是否为有效的客户帐号
	 * @param str
	 * @return
	 */
	public static boolean checkAccount(String str) {
		Pattern p = Pattern.compile("^[a-zA-Z0-9][\\w]{5,19}$");
		Matcher m = p.matcher(str);
		return m.matches();
	}
	
	/**   
	 *   计算字符串长度.   一个汉字的长度按2计算.   如果给定的字符串为null,   返回0.   
	 *     
	 *   @param   str   
	 *                         待计算长度的字符串   
	 *   @return   字符串长度   
	 */
	public static int strlen(String str) {
		if (str == null || str.length() <= 0) {
			return 0;
		}

		int len = 0;

		char c;
		for (int i = str.length() - 1; i >= 0; i--) {
			c = str.charAt(i);
			if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z')
					|| (c >= 'A' && c <= 'Z')) {
				//字母,   数字   
				len++;
			} else {
				if (Character.isLetter(c)) { //中文   
					len += 2;
				} else { //符号或控制字符   
					len++;
				}
			}
		}

		return len;
	}   
	
	/**
	 * 将eMailAddress中的多余字符过滤掉如：fjlaflkjsldf<yuzhixinggiftedb@163.com>
	 * 从中取得yuzhixinggiftedb@163.com
	 * @param address
	 * @return
	 */
	public static String eMailAddressFilter(String address){
		StringBuffer stringBuffer = new StringBuffer();
		boolean flag_start = false;
		for(int i=0;i<address.length();i++){
			if(address.charAt(i)=='<'){
				flag_start = true;
				continue;
			}
			if(address.charAt(i)=='>'){
				flag_start = false;
			}
			if(flag_start == true){
				stringBuffer.append(address.charAt(i));
			}
		}
		return stringBuffer.toString();
	}
	
	/**
	 * 邮件MIME contentType类型处理
	 * 典型用法：
	 * 		"text/plain; name='=?gbk?Q?=C8=CE=CE=F1.txt?='";
	 * 		得到：text/plain
	 * @param contentType
	 * @return
	 * @author 于志兴
	 */
	public static String contentTypeHelper(String contentType){
		if(contentType == null || contentType.length() == 0){
			return null;
		}
		StringBuffer stringBuffer = new StringBuffer();
		for(int i=0;i<contentType.length();i++){
			if(contentType.charAt(i)==';'){
				break;
			}
			stringBuffer.append(contentType.charAt(i));
		}
		return stringBuffer.toString();
	}
	
	/**
	 * 获取一个文件名中的扩展名带 dot
	 * 典型用法：
	 * 		"yu.txt.jpg"
	 * 		得到：.jpg
	 * @param fileName
	 * @return
	 * @author 于志兴
	 */
	public static String getFileExtendNameWithDot(String fileName){
		StringBuffer stringBuffer = new StringBuffer();
		if(fileName.lastIndexOf('.')==-1){
			return ".noext";
		} else {
			stringBuffer.append(fileName.substring(fileName.lastIndexOf('.')));
			return stringBuffer.toString();
		}
	}
	
	/**
	 * 获取一个文件名中的扩展名不带 dot
	 * 典型用法：
	 * 		"yu.txt.jpg"
	 * 		得到：jpg
	 * @param fileName
	 * @return
	 * @author 于志兴
	 */
	public static String getFileExtendNameWithOutDot(String fileName){
		StringBuffer stringBuffer = new StringBuffer();
		if(fileName.lastIndexOf('.')==-1){
			return ".noext";
		} else {
			stringBuffer.append(fileName.substring(fileName.lastIndexOf('.')+1));
			return stringBuffer.toString();
		}
	}
	
	/**
	 * 根据串返回email地址
	 * @param tempStr
	 * @return
	 * @author yu
	 */
	public static ArrayList<String> getEmailAddressArray(String tempStr){
		String str[] = tempStr.split(",");
		ArrayList<String> listStr = new ArrayList<String>();
		for(int i=0;i<str.length;i++){
			if(str[i]!=null && StringUtils.isNotBlank(str[i])){
				System.out.println("第"+i+"个："+str[i]);
				listStr.add(str[i]);
			}
		}
		return listStr;
	}
}
